/*
 * @Author: shenzhiwei
 * @Date: 2024-7-4 11:04:42
 * @Company: orientsec.com.cn
 * @Description: 实现APP分享至微信，在微信内可直接唤醒APP并最终到目标页
 */

import CallApp from "callapp-lib";
import { detect, isFromApp, isFromWeiBo, isFromWeiXin } from "./utils";
import { wxInstance } from "./wxInstance";
import VConsole from "vconsole";
import "./styles.scss"

interface CallAppParams {
  configuration?: any;
}

const newCallLib = new CallApp({
  // 用来配置 URL Scheme
  scheme: {
    protocol: "dfyj20170811",
  }, // APP 的 App Store 地址
  appstore: "https://itunes.apple.com/cn/app/id961539789", // APP 的应用宝地址，如果不填写，则安卓微信中会直接跳转 fallback
  yingyongbao: "//a.app.qq.com/o/simple.jsp?pkgname=com.dfzq.winner",
  fallback:
    "https://cfyjh5-v3.dfzq.com.cn/html5-marketing/marketing-install/index.html", // 等待唤端的时间（单位: ms），超时则判断为唤端失败，目前定义为3秒等待时间
  timeout: 3000, // Universal Link，该配置仅用于iOS平台使用
  universal: {
    // 生产环境
    host: "appullinks.dfzq.com.cn", // // 测试环境
    // host: "h5itest1.dfzq.com.cn"
  },
});

/**
 * 非app展示DOM标签，一般呈现在页面的底部或者顶部，目前赢家APP呈现在底部
 */
const addButtonHtml = () => {
  const html = document.createElement("div");
  html.className = "ui-row-flex shareNavigation";
  html.id = "wraper";
  document.body.appendChild(html);
  const iconTtml = document.createElement("div");
  const span1 = document.createElement("span");
  span1.innerText = "东方证券";
  const span2 = document.createElement("span");
  span2.innerText = "悦享投资之美";
  iconTtml.className = "logoImage";
  const iconWraperhtml = document.createElement("div");
  iconWraperhtml.className = "ui-col-2";
  const logoTextHtml = document.createElement("div");
  logoTextHtml.className = "logoText";
  logoTextHtml.appendChild(span1);
  logoTextHtml.appendChild(span2);
  const buttonWraperhtml = document.createElement("div");
  const buttonHtml = document.createElement("button");
  buttonHtml.innerText = "立即打开";
  buttonWraperhtml.className = "open";
  buttonWraperhtml.id = "btnLaunchAppNew";
  iconWraperhtml.appendChild(iconTtml);
  iconWraperhtml.appendChild(logoTextHtml);
  buttonWraperhtml.appendChild(buttonHtml);
  html.appendChild(iconWraperhtml);
  html.appendChild(buttonWraperhtml);
};

/**
 * 安卓开放标签
 */
const addOpenButtonHtml = () => {
  const html = document.createElement("div");
  html.className = "ui-row-flex shareNavigation";
  html.id = "wraper";
  document.body.appendChild(html);
  const iconTtml = document.createElement("div");
  const span1 = document.createElement("span");
  span1.innerText = "东方证券";
  const span2 = document.createElement("span");
  span2.innerText = "悦享投资之美";
  iconTtml.className = "logoImage";
  const iconWraperhtml = document.createElement("div");
  iconWraperhtml.className = "ui-col-2";
  const logoTextHtml = document.createElement("div");
  logoTextHtml.className = "logoText";
  logoTextHtml.appendChild(span1);
  logoTextHtml.appendChild(span2);
  const buttonWraperhtml = document.createElement("div");

  buttonWraperhtml.className = "open";
  buttonWraperhtml.id = "btnLaunchAppNew";
  iconWraperhtml.appendChild(iconTtml);
  iconWraperhtml.appendChild(logoTextHtml);

  // todo
  // buttonWraperhtml.innerHTML = `
  //   <wx-open-launch-app id="launch-btn" appid="wxe9155ec6465b12c0" extinfo="dfyj20170811://dl/wb?url=${encodeURIComponent(location.href)}">
  //       <script type="text/wxtag-template">
  //         <style>.btn { font-size: 0.8rem; width: 5.60933rem; height: 1.9999rem; color: #fff; text-align: center; background: #ec2e31; border-radius: .42667rem; border: 0; margin-right: 1.28rem; margin-top: 0.5rem; outline: 0; }</style>
  //         <button class="btn">立即打开</button>
  //       </script>
  //    </wx-open-launch-app>';
  //   `;
  buttonWraperhtml.innerHTML = `
    <wx-open-launch-app id="launch-btn" appid="wxe9155ec6465b12c0" extinfo="dfyj20170811://dl/wb?url=${encodeURIComponent(location.href)}">
        <script type="text/wxtag-template">
          <style>.btn { padding:12px }</style>
          <button class="btn">立即打开</button>
        </script>
     </wx-open-launch-app>';
    `;
  // buttonWraperhtml.innerHTML =
  //    '<wx-open-launch-app id="launch-btn" appid="wxf1ff7161cbbb4db2" extinfo="dfyj20170811://dl/wb?url=' +
  //      location.href +
  //    '"><script type="text/wxtag-template"><style>.btn { font-size: 0.8rem; width: 5.60933rem; height: 1.9999rem; color: #fff; text-align: center; background: #ec2e31; border-radius: .42667rem; border: 0; margin-right: 1.28rem; margin-top: 0.5rem; outline: 0; }</style><button class="btn">立即打开</button></script></wx-open-launch-app>';
  html.appendChild(iconWraperhtml);
  html.appendChild(buttonWraperhtml);
};

/**
 * 默认跳转处理，一般用于跳转APP下载页
 * @param params 传参
 * @returns
 */
const callBack = (params: CallAppParams = {}) => {
  return "https://cfyjh5-v3.dfzq.com.cn/html5-marketing/marketing-install/index.html";
};

/**
 * UniversalLink链接生成器（目前APP已强升至5.13.0）
 * @returns 返回一个iOS可解析的 universalUrl
 *
 * 采用三次编码约定：（针对<5.9.0的iOS版本，使用open=来接受，可使用 https://websanova.com/utils/url 进行测试）
 * 步骤一. 对目标地址（https://{domain}/{path}/?qs#/hash?qs）中2个 qs 部分进行编码形成 queryStringEncoder；
 * 步骤二. 再对 https://{domain}/{path}/?queryStringEncoder 进行编码形成 targetUrlEncoder；
 * 步骤三. 再对 dfyj20170811://dl/wb?url=targetUrlEncoder 进行再编码形成 schemaUrlEncoder；
 * 步骤四. 最终形成规范地址：https://appullinks.dfzq.com.cn/dfyjlink?open=schemaUrlEncoder；
 *
 * 采用二次编码约定：（针对>=5.9.0的iOS版本，使用callapp=来接受）
 * 步骤一. 对 location.href 进行编码形成 targetUrlEncoder；
 * 步骤二. 对 dfyj20170811://dl/wb?url=targetUrlEncoder 进行再编码形成 schemaUrlEncoder；
 * 步骤三. 最终形成规范地址：https://appullinks.dfzq.com.cn/dfyjlink?open=schemaUrlEncoder；
 *
 * 注意：open和callapp需要同时携带在url上，open=用于<5.9.0的兼容，callapp=则是用于>=5.9.0的兼容
 */
const universalurl = () => {
  // 情况1：http://192.168.114.160:10086/?recommend=1&appversion=5.7.3#/pages/fundSubscribeDetail/index?prodCode=000395
  // 情况2：http://192.168.114.160:10086/?recommend=1&appversion=5.7.3#/pages/fundSubscribeDetail/index
  // 情况3：http://192.168.114.160:10086/#/pages/fundSubscribeDetail/index?prodCode=000395
  // 经分析，hash部分中可能存在 qs，同时 qs 也可能出现在标准体html后！另外 recommend 和 appversion 作为原生分享出来的派生参数。

  // @ts-ignore
  const parser = window.url;
  let targetUrl = location.href;
  console.log("[UL]targetUrl: " + targetUrl);
  // 兼容 <5.9.0 的iOS版本
  // 步骤一
  // 页面标准的 qs 编码
  const queryString = parser("query", targetUrl) || "";
  let queryStringEncoder = "";
  if (queryString) {
    console.log("[UL]queryString: " + queryString);
    queryStringEncoder = window.encodeURIComponent(queryString);
    targetUrl = targetUrl.replace(queryString, queryStringEncoder);
  }
  // 页面标准的 hash 编码，需带#
  const hash = parser("hash", targetUrl);
  let hashEncoder = "";
  if (hash) {
    // 检测 hash 部分中是否包含 qs 部分
    const hashQsString = parser("query", hash);
    if (hashQsString) {
      console.log("[UL]hashQsString: " + hashQsString);
      const hashQsStringEncoder = window.encodeURIComponent(hashQsString);
      targetUrl = targetUrl.replace(hashQsString, hashQsStringEncoder);
    }
  }

  // 步骤二
  const targetUrlEncoder = window.encodeURIComponent(targetUrl);
  console.log("[UL]targetUrlEncoder: " + targetUrlEncoder);

  // 步骤三
  const schemaUrlEncoder = window.encodeURIComponent(
    `dfyj20170811://dl/wb?url=${targetUrlEncoder}`,
  );
  console.log("[UL]schemaUrlEncoder: " + schemaUrlEncoder);

  // 步骤四
  const universalLink = `https://appullinks.dfzq.com.cn/dfyjlink?open=${schemaUrlEncoder}`;
  console.log("[UL]universalLink: " + universalLink);

  // 兼容 >=5.9.0 的iOS版本
  // 步骤一
  // 对 location.href 进行编码形成 targetUrlEncoder
  const targetUrlEncoder2 = window.encodeURIComponent(location.href);
  console.log("[UL]targetUrlEncoder2: " + targetUrlEncoder2);

  // 步骤二. 对 dfyj20170811://dl/wb?url=targetUrlEncoder 进行再编码形成 schemaUrlEncoder；
  const schemaUrlEncoder2 = window.encodeURIComponent(
    `dfyj20170811://dl/wb?url=${targetUrlEncoder2}`,
  );
  console.log("[UL]schemaUrlEncoder2: " + schemaUrlEncoder2);

  // 步骤三
  const universalLink2 = `${universalLink}&callapp=${schemaUrlEncoder2}`;
  console.log("[UL]universalLink2: " + universalLink2);

  return universalLink2;
};

/**
 * 唤起app打开当前location.href
 * @param params  fastmanV3时不用传
 */
const callAppLH = (params: CallAppParams = {}) => {
  // if (detect.os.ios && isFromWeiXin()) {
  if (detect.os.ios) {
    let targetUniversalLinkUrl = universalurl();
    // 示例targetUniversalLinkUrl：https://appullinks.dfzq.com.cn/dfyjlink/?open=dfyj20170811%3A%2F%2Fdl%2Fwb%3Furl%3Dhttp%253A%252F%252F192.168.92.217%253A10086%252F%2523%252Fpages%252FfundPurchaseDetail%252Findex&callapp=dfyj20170811%3A%2F%2Fdl%2Fwb%3Furl%3Dhttp%253A%252F%252F192.168.92.217%253A10086%252F%2523%252Fpages%252FfundPurchaseDetail%252Findex
    // 非pathKey模式，Universal Link 拼接规则：const universalLink = `https://${host}/${open方法中的path}?${open方法中param转换的queryString}`;
    // @ts-ignore
    const parser = window.url;
    try {
      // 可提炼出 queryString 的对象
      let param = parser("?", targetUniversalLinkUrl) || {};
      // 可提炼出/dfyjlink字符串
      let path = parser("1", targetUniversalLinkUrl);
      newCallLib.open({
        path,
        param,
        callback() {
          // 自定义唤端失败回调函数：进入下载页
          console.log("自定义唤端失败回调函数：进入下载页");
          location.href = callBack(params);
        },
      });
    } catch (err) {
      // 容错保护，一旦发生parser解析异常，最低限度确保用户可以跳转，而不会引导跳转下载页
      location.href = targetUniversalLinkUrl;
    }
  } else {
    newCallLib.open({
      path: `dl/wb?url=${encodeURIComponent(location.href)}`,
      callback() {
        // 自定义唤端失败回调函数：进入下载页
        console.log("自定义唤端失败回调函数：进入下载页");
        location.href = callBack(params);
      },
    });
  }
};

/**
 * 注册唤起事件
 * @param params 入参
 */
const registerLaunchApp = (params: CallAppParams = {}) => {
  // 动态植入底部标签DOM
  addButtonHtml();
  const btnHtml = document.getElementById("btnLaunchAppNew");
  btnHtml?.addEventListener("click", function () {
    callAppLH(params);
  });
};

/**
 * 样式为：页面下面有下载导航栏，点击导航栏中的立即打开按钮，浏览器里唤起app
 * @param params fastmanV2的config文件
 */
const launchApp = (params: CallAppParams = {}) => {
  // 非APP才生效此组件的作用
  if (!isFromApp()) {
    // 安卓端
    if (detect.os.android) {
      // 微信端：使用开放标签进行jssdk授权
      if (isFromWeiXin()) {
        wxInstance.configWx({
          accountNumber: "DFZQWLC",
          reqUrl: "https://wxs.dfzq.com.cn/RoxApiWeb/wxauth/getTicket",
          callback: () => {
            // 动态注入“开放标签DOM”
            addOpenButtonHtml();
            const btnHtml = document.getElementById("launch-btn");
            btnHtml?.addEventListener("launch", function (e) {
              console.log("success");
            });
            // 唤端失败处理
            btnHtml?.addEventListener("error", function (e) {
              console.error("fail", e);
              console.error("fail", e.detail);
              console.error("fail", e.detail.errMsg);
              callBack(params);
            });
            // 开放标签不支持
            document.addEventListener("WeixinOpenTagsError", function (e) {
              // 无法使用开放标签的错误原因，需回退兼容。仅无法使用开放标签，JS-SDK其他功能不受影响
              console.error("WeixinOpenTagsError", e);
              callBack(params);
            });
          },
        });
      }
      // 非微信端：使用SchemaURL
      else {
        registerLaunchApp(params);
      }
    }
    // iOS端
    else if (detect.os.ios) {
      registerLaunchApp(params);
    }
    // TODO 其他端后续处理....
  }
};

// @ts-ignore
// globalThis.launchApp = launchApp;
// @ts-ignore
window.launchApp = launchApp;
console.log(`launchApp 挂载完毕`);
const vConsole = new VConsole();

export { launchApp };
